package com.yyx.demo.config.statement;

import com.yyx.demo.config.Function;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MyHandler implements StatementHandler {

    public <T> T query(PreparedStatement statement, String parameter, Function function) throws SQLException, InvocationTargetException, IllegalAccessException, InstantiationException {
        ResultSet set = null;
        statement.setString(1,parameter.toString());
        set = statement.executeQuery();

        Class<T> tClass = null;

        //TODO set方法名和顺序未判断，建议list改为hash存储
        try {
            tClass = (Class<T>) Class.forName(function.getResultTypePath());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        T k=tClass.newInstance();
        Method[] methods = tClass.getDeclaredMethods();

        //声明一个数组，存方法
        List<Method> setMethods=new ArrayList<Method>();

        for (Method method : methods) {
            //若为set方法
            if(method.getName().startsWith("set")){
                setMethods.add(method);
            }
        }

        while (set.next()){
            int i=1;
            while (i<=setMethods.size()){
                setMethods.get(i-1).invoke(k,set.getString(i));
                i++;
            }
        }
        return k;
    }

    public PreparedStatement instantiateStatement(Connection connection,String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }
}
